import React, { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Scale, Clock, Trophy, Star, TrendingUp, AlertTriangle, CheckCircle, XCircle, Lightbulb, ArrowRight, Play } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface DecisionMakingTestProps {
  onComplete: (result: TestResult) => void;
}

interface Decision {
  id: number;
  type: 'probability' | 'risk' | 'multi-criteria' | 'temporal' | 'ethical' | 'strategic';
  scenario: string;
  options: DecisionOption[];
  correctChoice?: number;
  explanation?: string;
  timeLimit: number; // 秒
  difficulty: 'easy' | 'medium' | 'hard';
}

interface DecisionOption {
  id: number;
  description: string;
  probability?: number;
  reward?: number;
  risk?: number;
  value: number; // 客观价值评分
}

interface FeedbackState {
  show: boolean;
  correct: boolean;
  explanation: string;
  reactionTime: number;
  selectedOption: string;
  correctOption: string;
}

// 大幅扩展的题库
const DECISION_POOL: Decision[] = [
  // 投资理财类
  {
    id: 1,
    type: 'probability',
    scenario: '投资选择：您有10万元可以投资，需要选择最优策略',
    options: [
      { id: 0, description: '银行存款：年收益3%，几乎无风险', probability: 0.95, reward: 3000, value: 75 },
      { id: 1, description: '股票投资：可能收益15%，也可能亏损10%', probability: 0.6, reward: 15000, value: 80 },
      { id: 2, description: '基金投资：预期收益8%，风险适中', probability: 0.8, reward: 8000, value: 85 },
      { id: 3, description: '创业投资：可能翻倍，也可能全亏', probability: 0.3, reward: 100000, value: 60 }
    ],
    correctChoice: 2,
    explanation: '基金投资在风险和收益之间取得了最佳平衡，具有良好的风险收益比，适合大多数投资者的风险偏好',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 2,
    type: 'risk',
    scenario: '医疗决策：您需要选择治疗方案',
    options: [
      { id: 0, description: '保守治疗：成功率80%，恢复时间长', probability: 0.8, value: 70 },
      { id: 1, description: '手术治疗：成功率95%，但有5%严重并发症风险', probability: 0.95, value: 85 },
      { id: 2, description: '新药治疗：成功率85%，副作用轻微', probability: 0.85, value: 80 },
      { id: 3, description: '等待观察：无风险，但可能病情恶化', probability: 0.6, value: 40 }
    ],
    correctChoice: 1,
    explanation: '尽管有风险，但手术治疗的成功率最高，整体效益最大化，在医疗决策中应优先考虑治疗效果',
    timeLimit: 60,
    difficulty: 'hard'
  },
  {
    id: 3,
    type: 'multi-criteria',
    scenario: '工作选择：您需要在多个offer中选择',
    options: [
      { id: 0, description: '大公司：薪资高，但工作压力大，晋升慢', value: 75 },
      { id: 1, description: '初创公司：薪资中等，股权激励，风险较高', value: 70 },
      { id: 2, description: '外企：薪资很高，工作环境好，但发展空间有限', value: 80 },
      { id: 3, description: '国企：稳定，福利好，但创新机会少', value: 65 }
    ],
    correctChoice: 2,
    explanation: '外企在综合考虑薪资、环境、稳定性等因素后性价比最高，能够平衡短期收益和工作质量',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 4,
    type: 'temporal',
    scenario: '学习规划：距离考试还有3个月，如何分配时间？',
    options: [
      { id: 0, description: '平均分配：每科每天1小时，稳扎稳打', value: 75 },
      { id: 1, description: '重点突破：集中精力攻克薄弱科目', value: 85 },
      { id: 2, description: '强化优势：在已有优势基础上提升', value: 60 },
      { id: 3, description: '临时抱佛脚：前期轻松，最后一个月冲刺', value: 40 }
    ],
    correctChoice: 1,
    explanation: '重点突破薄弱环节能够最大化整体提升效果，符合边际效用递减规律，是最优的时间分配策略',
    timeLimit: 40,
    difficulty: 'easy'
  },
  {
    id: 5,
    type: 'probability',
    scenario: '保险购买：评估以下保险方案的性价比',
    options: [
      { id: 0, description: '基础保险：保费低，保障基本', probability: 0.9, value: 70 },
      { id: 1, description: '全面保险：保费高，保障全面', probability: 0.95, value: 80 },
      { id: 2, description: '专项保险：针对特定风险，性价比高', probability: 0.85, value: 85 },
      { id: 3, description: '不买保险：省钱，但承担全部风险', probability: 0.1, value: 30 }
    ],
    correctChoice: 2,
    explanation: '专项保险在成本和保障之间达到最佳平衡，针对性强且性价比高，避免过度保险和保险不足',
    timeLimit: 35,
    difficulty: 'medium'
  },
  {
    id: 6,
    type: 'strategic',
    scenario: '创业决策：您的初创项目面临资金短缺',
    options: [
      { id: 0, description: '寻找投资：可能稀释股权，但获得资金和资源', value: 80 },
      { id: 1, description: '银行贷款：利息负担重，但保持控制权', value: 65 },
      { id: 2, description: '暂停项目：保存实力，等待更好时机', value: 50 },
      { id: 3, description: '个人借贷：快速但风险极高', value: 35 }
    ],
    correctChoice: 0,
    explanation: '寻找投资能带来资金和战略资源，长期价值最高，是创业公司快速发展的最优策略',
    timeLimit: 55,
    difficulty: 'hard'
  },
  {
    id: 7,
    type: 'multi-criteria',
    scenario: '购房决策：在预算范围内选择最适合的房产',
    options: [
      { id: 0, description: '市中心小户型：地段好，升值潜力大，但空间小', value: 75 },
      { id: 1, description: '郊区大户型：空间大，环境好，但通勤不便', value: 70 },
      { id: 2, description: '学区房：教育资源好，但房龄较老', value: 80 },
      { id: 3, description: '新开发区：价格便宜，但配套不完善', value: 60 }
    ],
    correctChoice: 2,
    explanation: '学区房在长期价值和实用性方面具有优势，教育投资回报率高，保值增值能力强',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 8,
    type: 'temporal',
    scenario: '退休规划：40岁的您需要为退休做准备',
    options: [
      { id: 0, description: '激进投资：高风险高回报，时间充裕', value: 70 },
      { id: 1, description: '稳健配置：风险适中，收益稳定', value: 85 },
      { id: 2, description: '保守储蓄：风险极低，但收益有限', value: 60 },
      { id: 3, description: '暂不考虑：享受当下，未来再说', value: 20 }
    ],
    correctChoice: 1,
    explanation: '40岁适合稳健配置，平衡风险和收益，时间分散风险策略最优，为退休做好充分准备',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 9,
    type: 'probability',
    scenario: '新产品发布：市场推广策略选择',
    options: [
      { id: 0, description: '大规模营销：高投入，快速占领市场', probability: 0.7, value: 75 },
      { id: 1, description: '精准营销：成本适中，针对目标用户', probability: 0.85, value: 85 },
      { id: 2, description: '口碑营销：成本低，但传播速度慢', probability: 0.6, value: 65 },
      { id: 3, description: '不做推广：节省成本，依靠产品本身', probability: 0.3, value: 40 }
    ],
    correctChoice: 1,
    explanation: '精准营销具有最佳的成功概率和投入产出比，能够有效触达目标用户群体，是最理性的选择',
    timeLimit: 40,
    difficulty: 'medium'
  },
  {
    id: 10,
    type: 'risk',
    scenario: '股票投资：市场波动中的投资策略',
    options: [
      { id: 0, description: '全仓买入：抓住机会，但风险极高', value: 50 },
      { id: 1, description: '分批建仓：降低风险，平摊成本', value: 85 },
      { id: 2, description: '观望等待：保守策略，可能错过机会', value: 60 },
      { id: 3, description: '借钱加杠杆：放大收益，风险翻倍', value: 30 }
    ],
    correctChoice: 1,
    explanation: '分批建仓是风险管理的最佳实践，能有效平摊成本和降低风险，是专业投资者的首选策略',
    timeLimit: 45,
    difficulty: 'medium'
  },
  
  // 职业发展类
  {
    id: 11,
    type: 'strategic',
    scenario: '职业转型：您在传统行业工作5年，考虑转入AI领域',
    options: [
      { id: 0, description: '直接跳槽：风险高，但机会大', value: 70 },
      { id: 1, description: '先学习再转：稳妥但时间成本高', value: 85 },
      { id: 2, description: '内部转岗：安全但机会有限', value: 65 },
      { id: 3, description: '保持现状：稳定但可能错过机会', value: 40 }
    ],
    correctChoice: 1,
    explanation: '先学习再转型是最稳妥的策略，能够降低转型风险并提高成功概率，时间投资换取长期价值',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 12,
    type: 'multi-criteria',
    scenario: '团队管理：如何处理团队内部的意见分歧',
    options: [
      { id: 0, description: '民主投票：公平但可能效率低', value: 75 },
      { id: 1, description: '专家意见：权威但可能忽视其他观点', value: 70 },
      { id: 2, description: '综合讨论：全面但耗时较长', value: 85 },
      { id: 3, description: '领导决定：快速但可能缺乏认同', value: 60 }
    ],
    correctChoice: 2,
    explanation: '综合讨论能够集思广益，提高决策质量和团队认同度，是最佳的团队决策方式',
    timeLimit: 45,
    difficulty: 'medium'
  },
  
  // 生活决策类
  {
    id: 13,
    type: 'temporal',
    scenario: '健康管理：30岁的您需要制定健康计划',
    options: [
      { id: 0, description: '高强度锻炼：快速见效，但难以坚持', value: 60 },
      { id: 1, description: '适度运动：循序渐进，容易养成习惯', value: 85 },
      { id: 2, description: '偶尔运动：压力小，但效果有限', value: 50 },
      { id: 3, description: '暂不运动：省时省力，但健康风险大', value: 20 }
    ],
    correctChoice: 1,
    explanation: '适度运动是最可持续的健康策略，既能保证效果又容易坚持，符合行为经济学原理',
    timeLimit: 35,
    difficulty: 'easy'
  },
  {
    id: 14,
    type: 'probability',
    scenario: '旅行计划：选择度假目的地',
    options: [
      { id: 0, description: '热门景点：设施完善，但人多价高', probability: 0.9, value: 70 },
      { id: 1, description: '小众目的地：独特体验，但风险较高', probability: 0.6, value: 75 },
      { id: 2, description: '周边游：方便安全，性价比高', probability: 0.95, value: 85 },
      { id: 3, description: '冒险旅行：刺激但风险极高', probability: 0.4, value: 50 }
    ],
    correctChoice: 2,
    explanation: '周边游在安全性、性价比和便利性方面都有优势，是最理性的旅行选择',
    timeLimit: 40,
    difficulty: 'easy'
  },
  
  // 商业决策类
  {
    id: 15,
    type: 'strategic',
    scenario: '市场竞争：面对强大竞争对手的策略',
    options: [
      { id: 0, description: '正面竞争：直接对抗，拼实力', value: 60 },
      { id: 1, description: '差异化竞争：避开锋芒，找细分市场', value: 85 },
      { id: 2, description: '价格战：降低利润，抢夺市场', value: 50 },
      { id: 3, description: '合作共赢：化敌为友，共同发展', value: 80 }
    ],
    correctChoice: 1,
    explanation: '差异化竞争是弱者战胜强者的最佳策略，通过细分市场找到自己的优势领域',
    timeLimit: 50,
    difficulty: 'hard'
  },
  {
    id: 16,
    type: 'risk',
    scenario: '产品研发：新技术投入决策',
    options: [
      { id: 0, description: '大量投入：抢占先机，但风险很高', value: 70 },
      { id: 1, description: '分阶段投入：控制风险，稳步推进', value: 85 },
      { id: 2, description: '等待观望：安全但可能落后', value: 50 },
      { id: 3, description: '跟随策略：降低风险，但错失先机', value: 65 }
    ],
    correctChoice: 1,
    explanation: '分阶段投入是创新项目的最佳策略，既能控制风险又能保持竞争力',
    timeLimit: 55,
    difficulty: 'hard'
  },
  
  // 教育决策类
  {
    id: 17,
    type: 'temporal',
    scenario: '子女教育：选择教育路径',
    options: [
      { id: 0, description: '公立学校：成本低，质量稳定', value: 75 },
      { id: 1, description: '私立学校：个性化教育，但费用高', value: 80 },
      { id: 2, description: '国际学校：国际化视野，适应性强', value: 85 },
      { id: 3, description: '在家教育：完全个性化，但社交不足', value: 60 }
    ],
    correctChoice: 2,
    explanation: '国际学校能够提供国际化视野和适应性培养，在全球化时代具有长远优势',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 18,
    type: 'multi-criteria',
    scenario: '技能学习：选择最有价值的技能',
    options: [
      { id: 0, description: '编程技能：需求大，但竞争激烈', value: 80 },
      { id: 1, description: '语言能力：通用性强，持续价值高', value: 85 },
      { id: 2, description: '专业技术：深度专精，但适用面窄', value: 70 },
      { id: 3, description: '软技能：应用广泛，难以量化', value: 75 }
    ],
    correctChoice: 1,
    explanation: '语言能力具有最强的通用性和持续价值，是最值得投资的技能',
    timeLimit: 45,
    difficulty: 'medium'
  },
  
  // 伦理决策类
  {
    id: 19,
    type: 'ethical',
    scenario: '环保选择：个人环保行为的取舍',
    options: [
      { id: 0, description: '极简生活：环保效果好，但生活质量下降', value: 70 },
      { id: 1, description: '绿色消费：平衡环保和生活质量', value: 85 },
      { id: 2, description: '技术环保：依靠科技解决环保问题', value: 80 },
      { id: 3, description: '维持现状：个人行为影响有限', value: 30 }
    ],
    correctChoice: 1,
    explanation: '绿色消费能够在环保和生活质量之间找到平衡，是最可持续的环保方式',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 20,
    type: 'ethical',
    scenario: '数据隐私：平衡便利性和隐私保护',
    options: [
      { id: 0, description: '完全保护：最大化隐私，但失去便利', value: 70 },
      { id: 1, description: '选择性分享：平衡隐私和便利', value: 85 },
      { id: 2, description: '信任平台：依赖平台自律', value: 60 },
      { id: 3, description: '无所谓：便利优先，忽视隐私', value: 40 }
    ],
    correctChoice: 1,
    explanation: '选择性分享是最理性的隐私策略，既能享受便利又能保护核心隐私',
    timeLimit: 40,
    difficulty: 'medium'
  },
  
  // 更多复杂场景...
  {
    id: 21,
    type: 'strategic',
    scenario: '危机管理：公司面临公关危机的处理策略',
    options: [
      { id: 0, description: '立即道歉：快速反应，但可能承认责任', value: 70 },
      { id: 1, description: '调查后回应：负责任但可能延误时机', value: 85 },
      { id: 2, description: '转移注意力：减少关注，但可能适得其反', value: 50 },
      { id: 3, description: '保持沉默：避免错误，但可能被质疑', value: 40 }
    ],
    correctChoice: 1,
    explanation: '调查后回应体现了负责任的态度，既能保证信息准确性又能维护公司形象',
    timeLimit: 60,
    difficulty: 'hard'
  },
  {
    id: 22,
    type: 'probability',
    scenario: '天气决策：户外活动遇到50%降雨概率',
    options: [
      { id: 0, description: '如期进行：享受活动，但可能淋雨', probability: 0.5, value: 70 },
      { id: 1, description: '改为室内：安全但体验不同', probability: 0.9, value: 75 },
      { id: 2, description: '延期举行：等待好天气', probability: 0.8, value: 85 },
      { id: 3, description: '取消活动：避免风险，但失去机会', probability: 1.0, value: 40 }
    ],
    correctChoice: 2,
    explanation: '延期举行是最理性的选择，既能确保活动质量又能避免天气风险',
    timeLimit: 30,
    difficulty: 'easy'
  },
  {
    id: 23,
    type: 'multi-criteria',
    scenario: '时间管理：工作日程安排优化',
    options: [
      { id: 0, description: '严格计划：效率高但缺乏灵活性', value: 75 },
      { id: 1, description: '灵活安排：适应性强，效率稍低', value: 80 },
      { id: 2, description: '优先级管理：重要事项优先', value: 85 },
      { id: 3, description: '随性而为：自由但可能混乱', value: 50 }
    ],
    correctChoice: 2,
    explanation: '优先级管理是最有效的时间管理方法，能够确保重要事项得到充分关注',
    timeLimit: 35,
    difficulty: 'easy'
  },
  {
    id: 24,
    type: 'risk',
    scenario: '创新项目：是否投资未经验证的新技术',
    options: [
      { id: 0, description: '大胆投资：抢占先机，但风险极高', value: 65 },
      { id: 1, description: '小规模试点：控制风险，验证可行性', value: 85 },
      { id: 2, description: '等待验证：安全但可能错失机会', value: 60 },
      { id: 3, description: '完全拒绝：零风险但无收益', value: 30 }
    ],
    correctChoice: 1,
    explanation: '小规模试点是创新投资的最佳策略，既能验证技术可行性又能控制投资风险',
    timeLimit: 50,
    difficulty: 'hard'
  },
  {
    id: 25,
    type: 'temporal',
    scenario: '储蓄计划：如何分配月收入',
    options: [
      { id: 0, description: '激进储蓄：储蓄50%，生活质量下降', value: 70 },
      { id: 1, description: '平衡储蓄：储蓄20-30%，生活储蓄并重', value: 85 },
      { id: 2, description: '保守储蓄：储蓄10%，享受当下', value: 65 },
      { id: 3, description: '无储蓄：花光收入，及时行乐', value: 30 }
    ],
    correctChoice: 1,
    explanation: '平衡储蓄策略能够在当前生活质量和未来安全之间取得最佳平衡',
    timeLimit: 40,
    difficulty: 'medium'
  },
  
  // 继续添加更多题目...
  {
    id: 26,
    type: 'strategic',
    scenario: '人际关系：如何处理工作中的人际冲突',
    options: [
      { id: 0, description: '直接对话：坦诚沟通，但可能激化矛盾', value: 75 },
      { id: 1, description: '寻求调解：第三方介入，客观公正', value: 85 },
      { id: 2, description: '避免冲突：暂时回避，但问题未解决', value: 50 },
      { id: 3, description: '上级汇报：寻求权威，但可能损害关系', value: 60 }
    ],
    correctChoice: 1,
    explanation: '寻求调解是处理人际冲突的最佳方式，既能解决问题又能维护关系',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 27,
    type: 'probability',
    scenario: '购物决策：限时促销的购买选择',
    options: [
      { id: 0, description: '立即购买：抓住优惠，但可能冲动消费', probability: 0.7, value: 70 },
      { id: 1, description: '理性评估：考虑需求再决定', probability: 0.9, value: 85 },
      { id: 2, description: '等下次促销：错过优惠，但避免冲动', probability: 0.6, value: 75 },
      { id: 3, description: '放弃购买：节省金钱，但可能错过好产品', probability: 1.0, value: 60 }
    ],
    correctChoice: 1,
    explanation: '理性评估是最佳的购物策略，既能享受优惠又能避免冲动消费',
    timeLimit: 30,
    difficulty: 'easy'
  },
  {
    id: 28,
    type: 'ethical',
    scenario: '社会责任：发现公司的不当行为',
    options: [
      { id: 0, description: '内部举报：通过公司渠道解决', value: 80 },
      { id: 1, description: '外部举报：寻求外部监督', value: 85 },
      { id: 2, description: '私下提醒：非正式沟通', value: 60 },
      { id: 3, description: '保持沉默：避免麻烦，但违背良心', value: 20 }
    ],
    correctChoice: 1,
    explanation: '外部举报是最有效的解决方式，能够确保问题得到公正处理',
    timeLimit: 55,
    difficulty: 'hard'
  },
  {
    id: 29,
    type: 'multi-criteria',
    scenario: '养老规划：50岁时的养老准备策略',
    options: [
      { id: 0, description: '增加储蓄：保守但收益有限', value: 70 },
      { id: 1, description: '多元投资：平衡风险和收益', value: 85 },
      { id: 2, description: '购买保险：转移风险，但成本较高', value: 75 },
      { id: 3, description: '依靠子女：传统但增加子女负担', value: 50 }
    ],
    correctChoice: 1,
    explanation: '多元投资是最佳的养老策略，能够在风险可控的前提下实现财富增值',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 30,
    type: 'temporal',
    scenario: '技能提升：工作5年后的发展规划',
    options: [
      { id: 0, description: '深化专业：在现有领域深耕', value: 75 },
      { id: 1, description: '拓展技能：学习相关新技能', value: 85 },
      { id: 2, description: '转换跑道：完全改变职业方向', value: 65 },
      { id: 3, description: '维持现状：稳定但可能落后', value: 40 }
    ],
    correctChoice: 1,
    explanation: '拓展技能是最佳的职业发展策略，既能保持专业优势又能适应市场变化',
    timeLimit: 45,
    difficulty: 'medium'
  },
  
  // 更多高难度题目
  {
    id: 31,
    type: 'strategic',
    scenario: '数字化转型：传统企业的转型策略',
    options: [
      { id: 0, description: '全面数字化：激进转型，风险较高', value: 70 },
      { id: 1, description: '渐进式转型：稳步推进，平衡新旧', value: 85 },
      { id: 2, description: '外包合作：借助外力，但依赖性强', value: 75 },
      { id: 3, description: '观望等待：保守但可能落后', value: 40 }
    ],
    correctChoice: 1,
    explanation: '渐进式转型能够最大化成功概率，既能保持业务稳定又能实现数字化目标',
    timeLimit: 60,
    difficulty: 'hard'
  },
  {
    id: 32,
    type: 'probability',
    scenario: '国际扩张：选择进入新市场的策略',
    options: [
      { id: 0, description: '直接投资：控制力强，但风险高', probability: 0.6, value: 75 },
      { id: 1, description: '合资经营：分担风险，共享收益', probability: 0.8, value: 85 },
      { id: 2, description: '授权代理：成本低，但控制力弱', probability: 0.7, value: 70 },
      { id: 3, description: '出口贸易：风险最小，但收益有限', probability: 0.9, value: 60 }
    ],
    correctChoice: 1,
    explanation: '合资经营是进入新市场的最佳策略，能够有效分担风险并利用当地资源',
    timeLimit: 55,
    difficulty: 'hard'
  },
  {
    id: 33,
    type: 'risk',
    scenario: '资产配置：经济不确定期的投资策略',
    options: [
      { id: 0, description: '现金为王：流动性最强，但收益很低', value: 60 },
      { id: 1, description: '防御性投资：稳健资产，抗风险能力强', value: 85 },
      { id: 2, description: '机会主义：寻找低估资产', value: 75 },
      { id: 3, description: '高风险投资：博取高收益', value: 50 }
    ],
    correctChoice: 1,
    explanation: '防御性投资是经济不确定期的最佳策略，能够在保值的基础上获得适度收益',
    timeLimit: 50,
    difficulty: 'hard'
  },
  {
    id: 34,
    type: 'ethical',
    scenario: 'AI伦理：如何平衡AI发展和伦理考量',
    options: [
      { id: 0, description: '快速发展：抢占先机，后续解决伦理问题', value: 60 },
      { id: 1, description: '伦理优先：建立框架，稳步发展', value: 85 },
      { id: 2, description: '国际合作：共同制定标准', value: 80 },
      { id: 3, description: '暂缓发展：等待伦理共识', value: 40 }
    ],
    correctChoice: 1,
    explanation: '伦理优先是AI发展的最佳方式，能够确保技术发展的可持续性和社会认同',
    timeLimit: 55,
    difficulty: 'hard'
  },
  {
    id: 35,
    type: 'multi-criteria',
    scenario: '全球供应链：后疫情时代的供应链策略',
    options: [
      { id: 0, description: '本土化：降低风险，但成本上升', value: 75 },
      { id: 1, description: '多元化：分散风险，提高韧性', value: 85 },
      { id: 2, description: '数字化：提高效率，增强透明度', value: 80 },
      { id: 3, description: '维持现状：成本最低，但风险集中', value: 50 }
    ],
    correctChoice: 1,
    explanation: '多元化供应链是最佳策略，能够在成本控制和风险管理之间取得平衡',
    timeLimit: 60,
    difficulty: 'hard'
  },
  
  // 继续添加更多场景，确保题库足够大...
  {
    id: 36,
    type: 'temporal',
    scenario: '职业转换：35岁考虑重新开始',
    options: [
      { id: 0, description: '立即行动：年龄优势，但经验归零', value: 70 },
      { id: 1, description: '渐进转换：保持收入，逐步过渡', value: 85 },
      { id: 2, description: '深造准备：提升能力，降低风险', value: 80 },
      { id: 3, description: '放弃想法：现实考虑，维持稳定', value: 40 }
    ],
    correctChoice: 1,
    explanation: '渐进转换是最理智的职业转换策略，既能保证生活稳定又能实现职业目标',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 37,
    type: 'strategic',
    scenario: '品牌建设：新品牌的市场定位策略',
    options: [
      { id: 0, description: '高端定位：利润丰厚，但市场有限', value: 70 },
      { id: 1, description: '大众市场：规模经济，但竞争激烈', value: 75 },
      { id: 2, description: '细分市场：精准定位，风险适中', value: 85 },
      { id: 3, description: '低价策略：快速占领，但利润微薄', value: 60 }
    ],
    correctChoice: 2,
    explanation: '细分市场定位是新品牌的最佳策略，能够在竞争中找到自己的立足点',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 38,
    type: 'probability',
    scenario: '健康检查：发现轻微异常的处理方式',
    options: [
      { id: 0, description: '立即深度检查：彻底排查，但可能过度医疗', probability: 0.9, value: 80 },
      { id: 1, description: '定期观察：谨慎监控，平衡成本效益', probability: 0.85, value: 85 },
      { id: 2, description: '改善生活方式：自然调理', probability: 0.7, value: 75 },
      { id: 3, description: '忽略异常：节省费用，但可能延误', probability: 0.3, value: 30 }
    ],
    correctChoice: 1,
    explanation: '定期观察是最理性的健康管理方式，既能及时发现问题又能避免过度医疗',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 39,
    type: 'risk',
    scenario: '创业融资：选择投资方的考虑',
    options: [
      { id: 0, description: '知名VC：品牌价值高，但条件苛刻', value: 75 },
      { id: 1, description: '战略投资者：资源丰富，协同效应强', value: 85 },
      { id: 2, description: '天使投资：条件宽松，但资金有限', value: 70 },
      { id: 3, description: '银行贷款：成本固定，但还款压力大', value: 60 }
    ],
    correctChoice: 1,
    explanation: '战略投资者能够提供资金以外的资源支持，是创业公司的最佳选择',
    timeLimit: 55,
    difficulty: 'hard'
  },
  {
    id: 40,
    type: 'ethical',
    scenario: '信息透明：如何平衡透明度和商业秘密',
    options: [
      { id: 0, description: '完全透明：建立信任，但可能泄露机密', value: 70 },
      { id: 1, description: '选择性透明：平衡利益，保护核心信息', value: 85 },
      { id: 2, description: '最低透明：法律要求，保护商业利益', value: 60 },
      { id: 3, description: '拒绝透明：保密至上，但影响信任', value: 40 }
    ],
    correctChoice: 1,
    explanation: '选择性透明是最佳的信息管理策略，既能建立信任又能保护商业利益',
    timeLimit: 50,
    difficulty: 'medium'
  },
  
  // 继续增加到50+题目...
  {
    id: 41,
    type: 'multi-criteria',
    scenario: '团队招聘：选择新团队成员的标准',
    options: [
      { id: 0, description: '技能优先：专业能力强，但团队适应性未知', value: 75 },
      { id: 1, description: '综合评估：技能与文化适配并重', value: 85 },
      { id: 2, description: '文化匹配：团队和谐，但可能缺乏多样性', value: 70 },
      { id: 3, description: '成本考虑：经济实用，但质量可能不足', value: 50 }
    ],
    correctChoice: 1,
    explanation: '综合评估是最佳的招聘策略，既能保证专业能力又能维护团队文化',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 42,
    type: 'temporal',
    scenario: '技术更新：软件系统的升级时机',
    options: [
      { id: 0, description: '立即升级：享受新功能，但可能有bug', value: 70 },
      { id: 1, description: '等待稳定版：安全可靠，错过早期优势', value: 85 },
      { id: 2, description: '分批升级：降低风险，但管理复杂', value: 80 },
      { id: 3, description: '延迟升级：稳定至上，但可能落后', value: 60 }
    ],
    correctChoice: 1,
    explanation: '等待稳定版是最理性的升级策略，能够平衡新功能和系统稳定性',
    timeLimit: 40,
    difficulty: 'medium'
  },
  {
    id: 43,
    type: 'probability',
    scenario: '投资时机：市场低迷时的投资决策',
    options: [
      { id: 0, description: '抄底投资：风险高，但收益可观', probability: 0.6, value: 75 },
      { id: 1, description: '定投策略：分散风险，平摊成本', probability: 0.8, value: 85 },
      { id: 2, description: '等待反弹：保守观望', probability: 0.7, value: 65 },
      { id: 3, description: '撤离市场：避免损失，但错过机会', probability: 0.9, value: 50 }
    ],
    correctChoice: 1,
    explanation: '定投策略是市场低迷时的最佳投资方式，能够有效降低时间风险',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 44,
    type: 'strategic',
    scenario: '客户关系：处理重要客户的不合理要求',
    options: [
      { id: 0, description: '完全满足：维护关系，但可能开坏先例', value: 60 },
      { id: 1, description: '协商解决：寻求双赢方案', value: 85 },
      { id: 2, description: '坚持原则：维护公司利益，但可能失去客户', value: 70 },
      { id: 3, description: '转介其他：避免冲突，但可能丢失业务', value: 50 }
    ],
    correctChoice: 1,
    explanation: '协商解决是处理客户关系的最佳方式，既能维护关系又能保护公司利益',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 45,
    type: 'risk',
    scenario: '新市场进入：评估进入壁垒和机会',
    options: [
      { id: 0, description: '强行进入：不惧壁垒，快速行动', value: 65 },
      { id: 1, description: '寻找切入点：巧妙进入，降低阻力', value: 85 },
      { id: 2, description: '合作进入：借助伙伴，分担风险', value: 80 },
      { id: 3, description: '放弃进入：避免风险，但错失机会', value: 40 }
    ],
    correctChoice: 1,
    explanation: '寻找切入点是最聪明的市场进入策略，能够以最小成本获得最大效果',
    timeLimit: 55,
    difficulty: 'hard'
  },
  {
    id: 46,
    type: 'ethical',
    scenario: '数据使用：客户数据的商业利用边界',
    options: [
      { id: 0, description: '最大化利用：充分挖掘数据价值', value: 50 },
      { id: 1, description: '征得同意：尊重用户意愿，合规使用', value: 85 },
      { id: 2, description: '最小化使用：保守使用，避免争议', value: 70 },
      { id: 3, description: '不使用数据：完全保护隐私，但放弃价值', value: 60 }
    ],
    correctChoice: 1,
    explanation: '征得同意是数据使用的最佳实践，既能创造价值又能保护用户权益',
    timeLimit: 50,
    difficulty: 'medium'
  },
  {
    id: 47,
    type: 'multi-criteria',
    scenario: '办公模式：后疫情时代的工作安排',
    options: [
      { id: 0, description: '全面返回办公室：加强协作，但缺乏灵活性', value: 70 },
      { id: 1, description: '混合办公模式：平衡效率和灵活性', value: 85 },
      { id: 2, description: '完全远程：最大灵活性，但协作困难', value: 65 },
      { id: 3, description: '因人而异：个性化安排，但管理复杂', value: 75 }
    ],
    correctChoice: 1,
    explanation: '混合办公模式是最佳的工作安排，既能保持团队协作又能提供工作灵活性',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 48,
    type: 'temporal',
    scenario: '知识更新：专业知识的持续学习策略',
    options: [
      { id: 0, description: '密集学习：短期提升，但可能burnout', value: 70 },
      { id: 1, description: '持续学习：细水长流，效果持久', value: 85 },
      { id: 2, description: '按需学习：实用主义，但可能滞后', value: 75 },
      { id: 3, description: '停止学习：节省时间，但知识老化', value: 30 }
    ],
    correctChoice: 1,
    explanation: '持续学习是最佳的知识更新策略，能够保持专业竞争力和适应性',
    timeLimit: 40,
    difficulty: 'easy'
  },
  {
    id: 49,
    type: 'probability',
    scenario: '产品定价：新产品的价格策略',
    options: [
      { id: 0, description: '高价策略：建立高端形象，但市场有限', probability: 0.6, value: 70 },
      { id: 1, description: '渗透定价：快速获得市场份额', probability: 0.8, value: 85 },
      { id: 2, description: '跟随定价：安全稳妥，但缺乏差异化', probability: 0.7, value: 65 },
      { id: 3, description: '成本加成：简单直接，但可能缺乏竞争力', probability: 0.5, value: 55 }
    ],
    correctChoice: 1,
    explanation: '渗透定价是新产品的最佳策略，能够快速建立市场地位和用户基础',
    timeLimit: 45,
    difficulty: 'medium'
  },
  {
    id: 50,
    type: 'strategic',
    scenario: '危机预防：建立企业风险管理体系',
    options: [
      { id: 0, description: '全面防控：投入大量资源，但成本高昂', value: 75 },
      { id: 1, description: '重点防控：聚焦关键风险，效率最优', value: 85 },
      { id: 2, description: '保险转移：通过保险转移风险', value: 70 },
      { id: 3, description: '接受风险：节省成本，但承担后果', value: 40 }
    ],
    correctChoice: 1,
    explanation: '重点防控是最有效的风险管理策略，能够以最少资源获得最大保护效果',
    timeLimit: 55,
    difficulty: 'hard'
  }
];

export function DecisionMakingTest({ onComplete }: DecisionMakingTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentDecisionIndex, setCurrentDecisionIndex] = useState(0);
  const [selectedDecisions, setSelectedDecisions] = useState<Decision[]>([]);
  const [responses, setResponses] = useState<number[]>([]);
  const [reactionTimes, setReactionTimes] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(720); // 12分钟
  const [decisionTimeLeft, setDecisionTimeLeft] = useState(0);
  const [startTime, setStartTime] = useState<number>(0);
  const [decisionStartTime, setDecisionStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [feedback, setFeedback] = useState<FeedbackState>({
    show: false,
    correct: false,
    explanation: '',
    reactionTime: 0,
    selectedOption: '',
    correctOption: ''
  });
  const [awaitingResponse, setAwaitingResponse] = useState(true);
  const [showContinueButton, setShowContinueButton] = useState(false);

  const TOTAL_DECISIONS = 10;
  const decision = selectedDecisions[currentDecisionIndex];
  const feedbackTimeoutRef = useRef<NodeJS.Timeout>();

  // 随机选择题目
  const selectRandomDecisions = () => {
    const shuffled = [...DECISION_POOL].sort(() => Math.random() - 0.5);
    return shuffled.slice(0, TOTAL_DECISIONS);
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
        
        setDecisionTimeLeft(prev => {
          if (prev <= 1) {
            // 时间到，自动选择第一个选项
            handleDecisionSelect(0, true);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  useEffect(() => {
    if (stage === 'test' && decision) {
      setDecisionTimeLeft(decision.timeLimit);
      setDecisionStartTime(Date.now());
      setAwaitingResponse(true);
      setShowContinueButton(false);
    }
  }, [currentDecisionIndex, stage]);

  const handleStartTest = () => {
    const decisions = selectRandomDecisions();
    setSelectedDecisions(decisions);
    setStage('test');
    setStartTime(Date.now());
    setDecisionStartTime(Date.now());
    setDecisionTimeLeft(decisions[0].timeLimit);
  };

  const handleDecisionSelect = (optionId: number, timeExpired = false) => {
    if (!awaitingResponse) return;
    
    const reactionTime = Date.now() - decisionStartTime;
    const isCorrect = optionId === decision.correctChoice;
    
    setAwaitingResponse(false);
    setResponses(prev => [...prev, optionId]);
    setReactionTimes(prev => [...prev, reactionTime]);
    
    // 优化的评分算法
    let points = 0;
    if (isCorrect) {
      points += 100; // 正确选择基础分
    } else {
      // 根据选项的客观价值给分
      const selectedOption = decision.options.find(opt => opt.id === optionId);
      points += selectedOption ? selectedOption.value : 0;
    }
    
    // 速度奖励（在合理时间内决策）
    const timeTaken = (decision.timeLimit - decisionTimeLeft);
    if (timeTaken < decision.timeLimit * 0.8 && !timeExpired) {
      points += Math.max(0, 30 - Math.floor(timeTaken / 5)); // 根据决策速度给予奖励
    }
    
    // 难度系数奖励
    const difficultyMultiplier = decision.difficulty === 'hard' ? 1.2 : 
                                 decision.difficulty === 'medium' ? 1.1 : 1.0;
    points = Math.round(points * difficultyMultiplier);
    
    // 决策复杂度奖励
    if (decision.type === 'multi-criteria' || decision.type === 'strategic' || decision.type === 'ethical') {
      points += 10; // 复杂决策类型额外奖励
    }
    
    setScore(prev => prev + points);
    
    // 准备详细反馈信息
    const selectedOptionDesc = decision.options[optionId].description;
    const correctOptionDesc = decision.correctChoice !== undefined 
      ? decision.options[decision.correctChoice].description 
      : '';
    
    setFeedback({
      show: true,
      correct: isCorrect,
      explanation: decision.explanation || '',
      reactionTime,
      selectedOption: selectedOptionDesc,
      correctOption: correctOptionDesc
    });
    
    // 显示继续按钮，不再自动跳转
    setShowContinueButton(true);
  };

  const handleContinue = () => {
    setFeedback(prev => ({ ...prev, show: false }));
    setShowContinueButton(false);
    setAwaitingResponse(true);
    
    if (currentDecisionIndex < selectedDecisions.length - 1) {
      setCurrentDecisionIndex(prev => prev + 1);
    } else {
      setStage('results');
    }
  };

  const handleComplete = () => {
    // 数据安全检查
    if (!responses.length || !reactionTimes.length || !selectedDecisions.length) {
      console.error('Incomplete test data for completion');
      return;
    }

    const correctDecisions = responses.filter((response, index) => 
      response === selectedDecisions[index].correctChoice
    ).length;
    
    // 优化的最终评分计算
    const maxPossibleScore = selectedDecisions.reduce((sum, decision) => {
      const difficultyMultiplier = decision.difficulty === 'hard' ? 1.2 : 
                                   decision.difficulty === 'medium' ? 1.1 : 1.0;
      const baseScore = 130; // 100基础分 + 30速度奖励
      const complexityBonus = (decision.type === 'multi-criteria' || 
                              decision.type === 'strategic' || 
                              decision.type === 'ethical') ? 10 : 0;
      return sum + Math.round((baseScore + complexityBonus) * difficultyMultiplier);
    }, 0);
    
    const finalScore = Math.round((score / maxPossibleScore) * 100);
    const averageReactionTime = Math.round(
      reactionTimes.reduce((sum, time) => sum + time, 0) / reactionTimes.length
    );
    
    // 分类统计 - 添加安全检查
    const typeGroups = {
      probability: selectedDecisions.filter(d => d.type === 'probability'),
      risk: selectedDecisions.filter(d => d.type === 'risk'),
      'multi-criteria': selectedDecisions.filter(d => d.type === 'multi-criteria'),
      temporal: selectedDecisions.filter(d => d.type === 'temporal'),
      ethical: selectedDecisions.filter(d => d.type === 'ethical'),
      strategic: selectedDecisions.filter(d => d.type === 'strategic')
    };
    
    const calculateTypeScore = (type: keyof typeof typeGroups) => {
      const typeDecisions = typeGroups[type];
      if (typeDecisions.length === 0) return 0;
      
      const correctCount = responses.filter((response, index) => 
        selectedDecisions[index] && selectedDecisions[index].type === type && 
        response === selectedDecisions[index].correctChoice
      ).length;
      
      return Math.round((correctCount / typeDecisions.length) * 100);
    };

    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 计算决策质量指数
    const decisionQualityIndex = Math.round(score / selectedDecisions.length);
    
    // 计算决策一致性（反应时间的稳定性）
    const rtMean = reactionTimes.reduce((sum, rt) => sum + rt, 0) / reactionTimes.length;
    const rtVariance = reactionTimes.reduce((sum, rt) => sum + Math.pow(rt - rtMean, 2), 0) / reactionTimes.length;
    const consistencyIndex = Math.max(0, 100 - Math.sqrt(rtVariance) / 100);

    // 计算难度分布
    const difficultyStats = {
      easy: selectedDecisions.filter(d => d.difficulty === 'easy').length,
      medium: selectedDecisions.filter(d => d.difficulty === 'medium').length,
      hard: selectedDecisions.filter(d => d.difficulty === 'hard').length
    };

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'decision-making',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalDecisions: selectedDecisions.length,
        correctDecisions,
        accuracy: Math.round((correctDecisions / selectedDecisions.length) * 100),
        averageReactionTime,
        probabilityDecisionAccuracy: calculateTypeScore('probability'),
        riskDecisionAccuracy: calculateTypeScore('risk'),
        multiCriteriaDecisionAccuracy: calculateTypeScore('multi-criteria'),
        temporalDecisionAccuracy: calculateTypeScore('temporal'),
        ethicalDecisionAccuracy: calculateTypeScore('ethical'),
        strategicDecisionAccuracy: calculateTypeScore('strategic'),
        decisionQualityIndex,
        totalScore: score,
        maxPossibleScore,
        consistencyIndex: Math.round(consistencyIndex),
        avgDecisionTime: Math.round(averageReactionTime / 1000 * 10) / 10,
        difficultyDistribution: difficultyStats,
        decisionTypes: Object.keys(typeGroups).map(type => ({
          type,
          count: typeGroups[type as keyof typeof typeGroups].length,
          accuracy: calculateTypeScore(type as keyof typeof typeGroups)
        }))
      }
    };

    onComplete(result);
  };

  // 清理定时器
  useEffect(() => {
    return () => {
      if (feedbackTimeoutRef.current) {
        clearTimeout(feedbackTimeoutRef.current);
      }
    };
  }, []);

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-violet-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-violet-600 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Scale className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">决策能力测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您在不确定情况下的决策质量</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-violet-50 to-purple-50 rounded-xl p-6 border border-violet-100">
              <h3 className="font-semibold text-violet-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>从50+题库中随机选择10个决策场景，确保每次体验都不同</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>包括概率判断、风险评估、多标准选择、伦理决策等6大类型</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>每个决策都有时间限制，需要快速判断</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>答题后显示详细反馈，手动点击继续下一题</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">5</span>
                  <p>评分考虑决策正确性、速度、难度和题型复杂度</p>
                </div>
              </div>
            </div>

            {/* 决策类型说明 */}
            <div className="grid grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2 flex items-center gap-2">
                  <TrendingUp className="w-4 h-4" />
                  概率判断
                </h4>
                <p className="text-sm text-blue-700">评估不确定性和期望收益</p>
              </div>
              <div className="bg-gradient-to-br from-red-50 to-red-100 rounded-xl p-4 border border-red-200">
                <h4 className="font-semibold text-red-800 mb-2 flex items-center gap-2">
                  <AlertTriangle className="w-4 h-4" />
                  风险评估
                </h4>
                <p className="text-sm text-red-700">权衡潜在风险和收益</p>
              </div>
              <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2 flex items-center gap-2">
                  <Scale className="w-4 h-4" />
                  多标准选择
                </h4>
                <p className="text-sm text-green-700">综合考虑多个因素</p>
              </div>
              <div className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl p-4 border border-orange-200">
                <h4 className="font-semibold text-orange-800 mb-2 flex items-center gap-2">
                  <Clock className="w-4 h-4" />
                  时间规划
                </h4>
                <p className="text-sm text-orange-700">长期vs短期利益权衡</p>
              </div>
              <div className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-4 border border-purple-200">
                <h4 className="font-semibold text-purple-800 mb-2 flex items-center gap-2">
                  <Lightbulb className="w-4 h-4" />
                  伦理决策
                </h4>
                <p className="text-sm text-purple-700">道德与利益的平衡</p>
              </div>
              <div className="bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl p-4 border border-indigo-200">
                <h4 className="font-semibold text-indigo-800 mb-2 flex items-center gap-2">
                  <Trophy className="w-4 h-4" />
                  战略思维
                </h4>
                <p className="text-sm text-indigo-700">长远规划和策略制定</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-violet-50 to-violet-100 rounded-xl border border-violet-200">
                <div className="text-2xl font-bold text-violet-600 mb-1">50+</div>
                <div className="text-sm text-violet-700">题库规模</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">6</div>
                <div className="text-sm text-purple-700">决策类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-violet-50 to-purple-50 rounded-xl border border-violet-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">12</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-violet-600 to-purple-500 hover:from-violet-700 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const progress = (currentDecisionIndex / selectedDecisions.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-violet-100 text-violet-700 border-violet-300">
              决策 {currentDecisionIndex + 1} / {selectedDecisions.length}
            </Badge>
            <Badge variant="outline" className={`${
              decision?.type === 'probability' ? 'bg-blue-100 text-blue-700 border-blue-300' :
              decision?.type === 'risk' ? 'bg-red-100 text-red-700 border-red-300' :
              decision?.type === 'multi-criteria' ? 'bg-green-100 text-green-700 border-green-300' :
              decision?.type === 'temporal' ? 'bg-orange-100 text-orange-700 border-orange-300' :
              decision?.type === 'ethical' ? 'bg-purple-100 text-purple-700 border-purple-300' :
              'bg-indigo-100 text-indigo-700 border-indigo-300'
            }`}>
              {decision?.type === 'probability' ? '概率判断' :
               decision?.type === 'risk' ? '风险评估' :
               decision?.type === 'multi-criteria' ? '多标准选择' :
               decision?.type === 'temporal' ? '时间规划' :
               decision?.type === 'ethical' ? '伦理决策' : '战略思维'}
            </Badge>
            <Badge variant="outline" className={`${
              decision?.difficulty === 'easy' ? 'bg-green-100 text-green-700 border-green-300' :
              decision?.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
              'bg-red-100 text-red-700 border-red-300'
            }`}>
              {decision?.difficulty === 'easy' ? '简单' :
               decision?.difficulty === 'medium' ? '中等' : '困难'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-4">
            <div className="text-center">
              <div className={`text-2xl font-bold font-mono ${decisionTimeLeft <= 10 ? 'text-red-500' : 'text-violet-700'}`}>
                {decisionTimeLeft}
              </div>
              <div className="text-xs text-slate-500">决策时间</div>
            </div>
            <div className="text-center">
              <div className="text-lg font-mono text-slate-600">
                {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
              </div>
              <div className="text-xs text-slate-500">总剩余</div>
            </div>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 决策场景 */}
        <Card className="bg-white/90 backdrop-blur-sm border-violet-200 shadow-lg relative">
          <CardHeader>
            <CardTitle className="text-xl text-slate-800">{decision?.scenario}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* 选项 */}
            <AnimatePresence>
              {!feedback.show && awaitingResponse && (
                <motion.div
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="space-y-3"
                >
                  {decision?.options.map((option) => (
                    <motion.div
                      key={option.id}
                      whileHover={{ scale: 1.01 }}
                      whileTap={{ scale: 0.99 }}
                    >
                      <Button
                        variant="outline"
                        onClick={() => handleDecisionSelect(option.id)}
                        className="w-full h-auto min-h-[4rem] text-left justify-start p-4 hover:bg-violet-50 hover:border-violet-300"
                      >
                        <div className="flex items-start gap-3">
                          <span className="w-8 h-8 bg-violet-100 text-violet-700 rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-1">
                            {String.fromCharCode(65 + option.id)}
                          </span>
                          <div className="text-left">
                            <p className="text-slate-800">{option.description}</p>
                            {option.probability && (
                              <p className="text-xs text-slate-500 mt-1">
                                成功概率: {Math.round(option.probability * 100)}%
                              </p>
                            )}
                          </div>
                        </div>
                      </Button>
                    </motion.div>
                  ))}
                </motion.div>
              )}
            </AnimatePresence>

            {/* 即时反馈显示 */}
            <AnimatePresence>
              {feedback.show && (
                <motion.div
                  initial={{ opacity: 0, scale: 0.9 }}
                  animate={{ opacity: 1, scale: 1 }}
                  exit={{ opacity: 0, scale: 0.9 }}
                  className="space-y-4"
                >
                  {/* 反馈卡片 */}
                  <div className={`p-6 rounded-xl border-2 ${
                    feedback.correct 
                      ? 'bg-green-50 border-green-200' 
                      : 'bg-orange-50 border-orange-200'
                  }`}>
                    {/* 反馈图标和标题 */}
                    <div className="flex items-center gap-3 mb-4">
                      <div className={`w-12 h-12 rounded-full flex items-center justify-center ${
                        feedback.correct ? 'bg-green-500' : 'bg-orange-500'
                      }`}>
                        {feedback.correct ? 
                          <CheckCircle className="w-6 h-6 text-white" /> : 
                          <XCircle className="w-6 h-6 text-white" />
                        }
                      </div>
                      <div>
                        <h3 className={`text-lg font-semibold ${
                          feedback.correct ? 'text-green-800' : 'text-orange-800'
                        }`}>
                          {feedback.correct ? '最优决策！' : '可以更好'}
                        </h3>
                        <p className="text-sm text-slate-600">
                          反应时间: {Math.round(feedback.reactionTime / 10) / 100}秒
                        </p>
                      </div>
                    </div>

                    {/* 您的选择 */}
                    <div className="mb-3">
                      <span className="text-sm font-medium text-slate-600">您的选择：</span>
                      <p className="text-slate-800 mt-1">{feedback.selectedOption}</p>
                    </div>

                    {/* 最优选择（如果选错了） */}
                    {!feedback.correct && (
                      <div className="mb-3">
                        <span className="text-sm font-medium text-slate-600">推荐选择：</span>
                        <p className="text-slate-800 mt-1">{feedback.correctOption}</p>
                      </div>
                    )}

                    {/* 解释 */}
                    {feedback.explanation && (
                      <div className="flex gap-3">
                        <Lightbulb className="w-5 h-5 text-amber-500 flex-shrink-0 mt-0.5" />
                        <div>
                          <span className="text-sm font-medium text-slate-600">解释：</span>
                          <p className="text-slate-700 mt-1">{feedback.explanation}</p>
                        </div>
                      </div>
                    )}
                  </div>

                  {/* 手动继续按钮 */}
                  <AnimatePresence>
                    {showContinueButton && (
                      <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        exit={{ opacity: 0, y: -20 }}
                        className="text-center"
                      >
                        <Button
                          onClick={handleContinue}
                          className="bg-gradient-to-r from-violet-600 to-purple-500 hover:from-violet-700 hover:to-purple-600 text-white px-8 py-3 font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
                        >
                          {currentDecisionIndex < selectedDecisions.length - 1 ? (
                            <>
                              下一题 <ArrowRight className="w-4 h-4 ml-2" />
                            </>
                          ) : (
                            <>
                              查看结果 <Play className="w-4 h-4 ml-2" />
                            </>
                          )}
                        </Button>
                      </motion.div>
                    )}
                  </AnimatePresence>
                </motion.div>
              )}
            </AnimatePresence>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    // 数据安全检查
    if (!responses.length || !reactionTimes.length || !selectedDecisions.length) {
      return (
        <div className="max-w-2xl mx-auto text-center p-8">
          <p className="text-slate-600">正在计算结果...</p>
        </div>
      );
    }

    const correctDecisions = responses.filter((response, index) => 
      response === selectedDecisions[index].correctChoice
    ).length;
    
    const maxPossibleScore = selectedDecisions.reduce((sum, decision) => {
      const difficultyMultiplier = decision.difficulty === 'hard' ? 1.2 : 
                                   decision.difficulty === 'medium' ? 1.1 : 1.0;
      const baseScore = 130;
      const complexityBonus = (decision.type === 'multi-criteria' || 
                              decision.type === 'strategic' || 
                              decision.type === 'ethical') ? 10 : 0;
      return sum + Math.round((baseScore + complexityBonus) * difficultyMultiplier);
    }, 0);
    
    const finalScore = Math.round((score / maxPossibleScore) * 100);
    const averageReactionTime = Math.round(
      reactionTimes.reduce((sum, time) => sum + time, 0) / reactionTimes.length
    );

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-violet-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-violet-600 to-purple-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-violet-600 to-purple-500 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">决策能力得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-violet-50 to-violet-100 rounded-xl border border-violet-200">
                <div className="text-2xl font-bold text-violet-600 mb-1">{correctDecisions}/{selectedDecisions.length}</div>
                <div className="text-sm text-violet-700">最优决策</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">{Math.round(averageReactionTime / 100) / 10}s</div>
                <div className="text-sm text-purple-700">平均决策时间</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">决策准确率</span>
                <span className="font-semibold text-slate-800">{Math.round((correctDecisions / selectedDecisions.length) * 100)}%</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">决策质量指数</span>
                <span className="font-semibold text-slate-800">{Math.round(score / selectedDecisions.length)}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">总得分</span>
                <span className="font-semibold text-slate-800">{score}/{maxPossibleScore}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">决策一致性</span>
                <span className="font-semibold text-slate-800">
                  {Math.round(Math.max(0, 100 - Math.sqrt(
                    reactionTimes.reduce((sum, rt) => {
                      const mean = reactionTimes.reduce((s, r) => s + r, 0) / reactionTimes.length;
                      return sum + Math.pow(rt - mean, 2);
                    }, 0) / reactionTimes.length
                  ) / 100))}%
                </span>
              </div>
            </div>

            <div className="bg-gradient-to-r from-violet-50 to-purple-50 rounded-xl p-4 border border-violet-100">
              <h3 className="font-semibold text-violet-900 mb-3 flex items-center gap-2">
                <Scale className="w-5 h-5" />
                题目构成
              </h3>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-slate-600">随机选择题目</span>
                  <span className="text-violet-600">{selectedDecisions.length}题</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">题库总规模</span>
                  <span className="text-purple-600">{DECISION_POOL.length}题</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-slate-600">题型覆盖</span>
                  <span className="text-slate-600">{new Set(selectedDecisions.map(d => d.type)).size}种</span>
                </div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-violet-600 to-purple-500 hover:from-violet-700 hover:to-purple-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}